package com.dobbinsoft.iotechn.device.mqtt.handler;

import com.dobbinsoft.iotechn.data.compent.CacheComponent;
import com.dobbinsoft.iotechn.device.api.biz.DeviceBizService;
import com.dobbinsoft.iotechn.device.constant.DeviceConst;
import com.dobbinsoft.iotechn.device.entity.DeviceSessionEntity;
import com.dobbinsoft.iotechn.device.enums.DeviceStatusType;
import com.dobbinsoft.iotechn.device.enums.IotMessageResultType;
import com.dobbinsoft.iotechn.device.enums.IotMessageType;
import com.dobbinsoft.iotechn.device.mqtt.message.IotDeviceDisconnectMessage;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Description:
 * User: rize
 * Date: 2020/6/26
 * Time: 16:46
 */
public class IotMqttDisconnectMessageHandler implements IotMqttMessageHandler<IotDeviceDisconnectMessage> {

    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private DeviceBizService deviceBizService;

    @Override
    public int handle(String accessKeyId, IotDeviceDisconnectMessage msg) {
        // 更新设备
        DeviceSessionEntity sessionEntity = cacheComponent.getHashObj(DeviceConst.CA_DEVICE_HASH, accessKeyId, DeviceSessionEntity.class);
        if (sessionEntity.getStatus().intValue() == DeviceStatusType.ONLINE.getCode()) {
            deviceBizService.offlineDevice(accessKeyId);
            sessionEntity.setStatus(DeviceStatusType.OFFLINE.getCode());
            cacheComponent.putHashObj(DeviceConst.CA_DEVICE_HASH, accessKeyId, sessionEntity);
        }
        // 未激活设备欲发送此消息，直接忽略
        return IotMessageResultType.SUCCESS.getCode();
    }

    @Override
    public int getCode() {
        return IotMessageType.DISCONNECT.getCode();
    }

    @Override
    public Class<IotDeviceDisconnectMessage> getMessageType() {
        return IotDeviceDisconnectMessage.class;
    }
}
